<?php

/**
 * This is the model class for table "{{menu_item}}".
 *
 * The followings are the available columns in table '{{menu_item}}':
 * @property integer $id
 * @property integer $menu_id
 * @property string $name
 * @property string $description
 * @property string $type
 * @property string $value
 * @property integer $parent_id
 * @property integer $rank
 * @property string $icon
 */
class MenuItem extends MyARContent
{

    public $tableName = 'menu_item';

    // Các loại menu

    const TYPE_LINK = 'link';
    const TYPE_POST = 'post';
    const TYPE_CONTROLLER = 'contro';
    const TYPE_CATEGORY = 'category';
    const TYPE_PRODUCT = 'product';
    const TYPE_PAGE = 'page';
    const TYPE_GENERAL = 'general';

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return MenuItem the static model class
     */
    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return '{{menu_item}}';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('menu_id, name, type', 'required'),
            array('menu_id, parent_id, rank', 'numerical', 'integerOnly' => true),
            array('name, description', 'length', 'max' => 250),
            array('type, icon', 'length', 'max' => 30),
            array('value', 'safe'),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, menu_id, name, description, type, value, parent_id, rank, icon', 'safe', 'on' => 'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        $ret = parent::relations();
        $ret['children'] = array(self::HAS_MANY, 'MenuItem', 'parent_id');
        $ret['parent'] = array(
            self::BELONGS_TO, 'MenuItem', 'parent_id');
        return $ret;
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        $array = array(
            'id' => 'ID',
            'menu_id' => 'Menu',
            'name' => 'Name',
            'description' => 'Description',
            'type' => 'Type',
            'value' => 'Value',
            'parent_id' => 'Parent',
            'rank' => 'Rank',
            'icon' => 'Icon',
        );
        foreach ($array as $key => $val)
        {
            $array[$key] = Yii::t('menuitem', $val);
        }

        return $array;
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search()
    {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('id', $this->id);
        $criteria->compare('menu_id', $this->menu_id);
        $criteria->compare('name', $this->name, true);
        $criteria->compare('description', $this->description, true);
        $criteria->compare('type', $this->type, true);
        $criteria->compare('value', $this->value, true);
        $criteria->compare('parent_id', $this->parent_id);
        $criteria->compare('rank', $this->rank);
        $criteria->compare('icon', $this->icon, true);

        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
        ));
    }

    function getObjectName()
    {
        return $this->name;
    }

    public static function getArrayType()
    {
        return array(
            self::TYPE_LINK => Yii::t('menuitem', 'Link to URL'),
            self::TYPE_CATEGORY => Yii::t('menuitem', 'Link to Category'),
            self::TYPE_CONTROLLER => 'Controller',
            self::TYPE_POST => Yii::t('menuitem', 'Link to Post'),
            self::TYPE_PAGE => Yii::t('menuitem', 'Link to Page'),
            self::TYPE_GENERAL => 'Trang tổng hợp',
        );
    }

    public static function getCateMenu($id)
    {
        $cri = new CDbCriteria;
        $cri->condition = "menu_id=:id and parent_id=:parent";
        $cri->params = array(
            ':parent' => 0,
            ':id' => $id,
        );
        $cri->order = 'rank DESC';
        $cates = MenuItem::model()->findAll($cri);
        foreach ($cates as $cate)
        {
            self::getSubCateMenu($cate);
        }
    }

    static function getSubCateMenu($cate)
    {
        $up = Yii::app()->controller->createUrl('menu/update', array(
            'lang' => Yii::app()->language,
            'pk' => $cate->menu_id,
            'parent' => $cate->id
        ));
        $del = Yii::app()->controller->createUrl('menu/deleteItems', array(
            'lang' => Yii::app()->language,
            'pk' => $cate->menu_id,
            'deleteItem' => $cate->id
        ));


        $action = "<div class='btn-group'>
                    <button class='btn dropdown-toggle action-menu' data-toggle='dropdown'>
                        $cate->name <span class='caret'></span>
                    </button>
                    <span class='dropdown-menu'>
                    <ul>
                         <li><a href='$up'><i class='icon-pencil'></i> Sửa</a></li>
                         <li><a href='$del'><i class='icon-trash'></i> Xóa</a></li>
                    </ul>
                    </span>
             </div>";

        if (!empty($cate->children))
        {
            echo "<li class='has-sub'> $action\n";
            echo "<ul>\n";
            foreach ($cate->children as $subcate)
            {
                self::getSubCateMenu($subcate);
            }
            echo "</ul>\n";
            echo "</li>\n";
        }
        else
        {
            echo "<li>$action</li>\n";
        }
    }

    /**
     * Lấy các phần tử Danh mục thành một mảng, sử dụng cho form bài viết khi chọn
     * danh mục hoặc form Danh mục khi chọn danh mục cha
     * 
     * @param array $blacklist Mảng các id của những category không muốn hiển thị trong ds này
     * @return array Một mảng các category với key là id, value là name
     */
    public static function getPublicArrayMenu($menu_id, $blacklist = array())
    {
        $root = array(
            0 => Yii::t('category', 'Danh mục cha')
        );
        $array = $root + self::getSub(0, $menu_id, $blacklist);
        return $array;
    }

    static function getSub($parent_id, $menu_id, $blacklist = array(), $separated = "|-- ")
    {
        $cri = new CDbCriteria;
        $cri->condition = "parent_id=:parent and menu_id=:id";
        $cri->params = array(
            ':parent' => $parent_id,
            ':id' => $menu_id,
        );
        $children = self::model()->findAll($cri);

        /* Lay danh sach cac thu muc con */
        $array = array();
        foreach ($children as $child)
        {
            if (in_array($child->id, $blacklist))
                continue;

            $array[$child->id] = $separated . $child->name;
            $childArray = self::getSub($child->id, $child->menu_id, $blacklist, $separated . "|-- ");
            if (!empty($childArray))
            {
                $array = $array + $childArray;
            }
        }


        return $array;
    }

}
